<!--
 * @Author: alan_mf
 * @Date: 2023-05-12 15:44:57
 * @LastEditors: upp24 1246815351@qq.com
 * @LastEditTime: 2023-07-25 14:14:36
 * @FilePath: /pure-admin-thin-i18n/src/views/order/endOrder/index.vue
 * @Description:
 *
-->

<template>
  <div v-if="order == `order`">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <span class="font-medium"> 菜单树结构 </span>
          <!-- <el-button type="primary" @click="handleClick">
          角色分配路由
        </el-button> -->
          <el-button type="primary" @click="handleAdd" v-auth="'per_add'">
            添加
          </el-button>
        </div>
      </template>
      <el-input
        class="mb-4"
        v-model="query"
        placeholder="请输入关键字查找"
        clearable
        @input="onQueryChanged"
      />
      <el-tree-v2
        ref="treeRef"
        :data="menus"
        :props="dataProps"
        :height="640"
        :filter-method="filterMethod"
      >
        <template #default="{ data }">
          <span>{{ transformI18n(data.title) }}</span>
          <div style="margin-left: 20px">
            <el-button
              v-if="data.level != '3'"
              type="success"
              :icon="useRenderIcon(AddFill)"
              circle
              style="width: 20px; height: 20px"
              @click="handleTwoAdd(data)"
              v-auth="'pei_route_add'"
            />
            <el-button
              type="warning"
              :icon="useRenderIcon(EditPen)"
              circle
              style="width: 20px; height: 20px"
              @click="handleTwoUpdata(data)"
              v-auth="'pei_route_mondify'"
            />
            <el-popconfirm
              title="是否确认删除?"
              @confirm="handleTwoDelete(data)"
            >
              <template #reference>
                <el-button
                  type="danger"
                  :icon="useRenderIcon(Delete)"
                  circle
                  style="width: 20px; height: 20px"
                  v-auth="'pei_route_delete'"
                />
              </template>
            </el-popconfirm>
          </div>
        </template>
      </el-tree-v2>
    </el-card>
    <el-dialog v-model="dialogAddrouter" title="添加路由">
      <el-form :model="formIs">
        <el-form-item label="路由名称" :label-width="formLabelWidth">
          <el-input
            v-model="formIs.title"
            autocomplete="off"
            placeholder="会员管理"
          />
        </el-form-item>
        <el-form-item label="路由地址" :label-width="formLabelWidth">
          <el-input
            v-model="formIs.path"
            autocomplete="off"
            placeholder="/member"
          />
        </el-form-item>
        <el-form-item
          v-if="level == 2"
          label="缓存标志"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="formIs.name"
            autocomplete="off"
            placeholder="Member"
          />
        </el-form-item>
        <el-form-item
          v-if="level == 1"
          label="路由重定向"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="formIs.redirect"
            autocomplete="off"
            placeholder="子路由地址/member/memberlist"
          />
        </el-form-item>
        <el-form-item
          v-if="level == 1"
          label="路由icon"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="formIs.icon"
            autocomplete="off"
            placeholder="home"
          />
        </el-form-item>
        <el-form-item label="路由状态" :label-width="formLabelWidth">
          <el-switch
            v-model="formIs.status"
            style="
              --el-switch-on-color: #13ce66;
              --el-switch-off-color: #ff4949;
            "
            inline-prompt
            active-value="1"
            inactive-value="2"
            active-text="正常"
            inactive-text="禁用"
            @change="onchange"
          />
        </el-form-item>
        <el-form-item
          v-if="level == 1"
          label="路由排序"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="formIs.rank"
            autocomplete="off"
            placeholder="数字（1，2，3...）"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogAddrouter = false" type="danger"
            >取消</el-button
          >
          <el-button type="primary" @click="handleAddSubmit()">
            提交
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
  <div
    v-else
    style="
      width: 100%;
      height: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 30px;
    "
  >
    <div>温馨提示：请联系开发人员操作此页面</div>
  </div>
</template>
<script setup lang="ts">
import { reactive, ref, computed, onMounted } from "vue";
import { clone } from "@pureadmin/utils";
import type { ElTreeV2 } from "element-plus";
import { transformI18n } from "@/plugins/i18n";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { useUserStoreHook } from "@/store/modules/user";
import type { TreeNode } from "element-plus/es/components/tree-v2/src/types";
import NodeTree from "@iconify-icons/ri/node-tree";
import AddFill from "@iconify-icons/ri/add-circle-line";
import Delete from "@iconify-icons/ep/delete";
import EditPen from "@iconify-icons/ep/edit-pen";
import { extractPathList, deleteChildren } from "@/utils/tree";
import {
  getAsyncAllRoutes,
  addAsyncRoutes,
  delAsyncRoutes,
  updateRoutes
} from "@/api/routes";
import { getRoleList } from "@/api/user";
import { message } from "@/utils/message";
import * as CryptoJS from "crypto-js";
defineOptions({
  name: "PermissionList"
});
const isEditRouter = ref("");
interface FormType {
  group_id: string;
  title: string;
  path: string;
  redirect: string;
  name: string;
  icon: string;
  rank: string;
  status: string;
  route_id: string;
}
onMounted(() => {
  getRouteList();
});
interface treeNode extends TreeNode {
  meta: {
    title: string;
  };
}
const formIs = reactive<FormType>({
  group_id: "",
  title: "",
  path: "",
  redirect: "",
  name: "",
  icon: "",
  rank: "",
  status: "",
  route_id: ""
});
const menus = ref([]);
const formLabelWidth = "120px";
const dialogAddrouter = ref(false);
const level = ref(0);
const roleList = ref([]);
const order = ref("order"); //是order 就是开发人员,不是就是管理员
// const menusTree = clone(usePermissionStoreHook().wholeMenus, true);
const query = ref("");
const dataProps = ref({
  value: "route_id",
  children: "children",
  label: "title"
});
const treeRef = ref<InstanceType<typeof ElTreeV2>>();
//获取角色列表
async function handleUserList() {
  if (order.value == "order") {
    const res = await getRoleList();
    if (res.code === 200) {
      roleList.value = res.data;
      message(res.msg, { type: "success" });
    } else {
      message(res.msg, { type: "error" });
    }
  }
}
//获取路由列表
const getRouteList = async () => {
  if (order.value == "order") {
    const res = await getAsyncAllRoutes();
    menus.value = res.data;
    handleUserList();
    console.log(res);
  }
};
const onQueryChanged = (query: string) => {
  (treeRef as any).value!.filter(query);
};
const filterMethod = (query: string, node: treeNode) => {
  return transformI18n(node.title)!.indexOf(query) !== -1;
};
//初始化弹窗
const initDialog = () => {
  formIs.group_id = "";
  formIs.title = "";
  formIs.path = "";
  formIs.redirect = "";
  formIs.name = "";
  formIs.icon = "";
  formIs.rank = "";
  formIs.status = "";
  formIs.route_id = "";
};
//添加路由
const handleAdd = () => {
  initDialog();
  formIs.group_id = "0";
  formIs.status = "1";
  dialogAddrouter.value = true;
};
//提交添加
const handleAddSubmit = async () => {
  if (isEditRouter.value == 0) {
    for (const key in formIs) {
      if (!formIs[key]) {
        delete formIs[key];
      }
    }
    const res = await addAsyncRoutes(formIs);
    if (res.code === 200) {
      location.reload();
      dialogAddrouter.value = false;
      message(res.msg, { type: "success" });
    } else {
      message(res.msg, { type: "error" });
    }
  } else {
    // for (const key in formIs) {
    //   if (!formIs[key]) {
    //     delete formIs[key];
    //   }
    // }
    console.log(formIs, "==----");
    updateRoutes(formIs).then(res => {
      if (res.code === 200) {
        location.reload();
        dialogAddrouter.value = false;
        message(res.msg, { type: "success" });
      } else {
        message(res.msg, { type: "error" });
      }
    });
    console.log("323322");
  }
};
//添加二级路由
const handleTwoAdd = (data: any) => {
  initDialog();
  formIs.status = "1";
  formIs.group_id = data.route_id;
  level.value = data.level + 1;
  isEditRouter.value = 0;
  dialogAddrouter.value = true;
};
//修改
const handleTwoUpdata = (data: any) => {
  formIs.route_id = data.route_id;
  formIs.title = data.title;
  formIs.path = data.path;
  formIs.redirect = data.redirect;
  formIs.name = data.name;
  formIs.icon = data.icon;
  formIs.rank = data.rank;
  level.value = data.level;
  if (data.status == "1") {
    formIs.status = "1";
  } else {
    formIs.status = "2";
  }
  isEditRouter.value = 2;
  dialogAddrouter.value = true;
};
//删除
const handleTwoDelete = async (data: any) => {
  console.log(JSON.parse(JSON.stringify(data)), data.route_id, "===--");
  // const roleJson = JSON.stringify({route_id: data.route_id});
  // const roleBase64 = CryptoJS.enc.Base64.stringify(
  //   CryptoJS.enc.Utf8.parse(roleJson)
  // );
  // const roleValue = {
  //  // };
  const params = {
    route_id: data.route_id
  };
  const res = await delAsyncRoutes(params);
  if (res.code === 200) {
    location.reload();
    message(res.msg, { type: "success" });
  } else {
    message(res.msg, { type: "error" });
  }
};
//路由状态修改
const onchange = (data: any) => {
  formIs.status = data;
  console.log(formIs.status);
};
</script>
